package org.codehaus.activemq.message;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import javax.jms.JMSException;

public class ResponseReceipt extends Receipt
{
  private Serializable result;
  private byte[] resultBytes;

  public int getPacketType()
  {
    return 25;
  }

  public Serializable getResult()
    throws JMSException
  {
    if (this.result == null) {
      if (this.resultBytes == null)
        return null;
      try
      {
        this.result = ((Serializable)new ObjectInputStream(new ByteArrayInputStream(this.resultBytes)).readObject());
      }
      catch (Exception e) {
        throw ((JMSException)new JMSException("Invalid network mesage received.").initCause(e));
      }
    }
    return this.result;
  }

  public void setResult(Serializable result)
  {
    this.result = result;
    this.resultBytes = null;
  }

  public void setResultBytes(byte[] resultBytes)
  {
    this.resultBytes = resultBytes;
    this.result = null;
  }

  public byte[] getResultBytes()
    throws IOException
  {
    if (this.resultBytes == null) {
      if (this.result == null) {
        return null;
      }
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ObjectOutputStream os = new ObjectOutputStream(baos);
      os.writeObject(this.result);
      os.close();
      this.resultBytes = baos.toByteArray();
    }
    return this.resultBytes;
  }
}